package com.shujia.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class Demo03StuProducer {
    public static void main(String[] args) throws IOException {

        Properties prop = new Properties();
        prop.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "master:9092,node1:9092,node2:9092");
        prop.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        prop.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer<String, String> producer = new KafkaProducer<>(prop);
        // 加载学生的数据
        BufferedReader br = new BufferedReader(new FileReader("kafka/data/student.txt"));
        String line;
        String topic = "stu01";
        while ((line = br.readLine()) != null) {
            // 写数据
            producer.send(new ProducerRecord<>(topic, line));
        }
        producer.flush();

        // 关闭连接
        producer.close();
        br.close();

        /**
         * 控制台消费：
         * kafka-console-consumer.sh --bootstrap-server master:9092 --topic stu01 --from-beginning
         */
    }
}
